/*
 * @Description: 
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-04-15 10:40:01
 * @LastEditors: ziwei
 * @LastEditTime: 2021-04-15 14:21:52
 */

//引入生成二叉树的方法
const Tree = require('./2.traversal.js');

//先序遍历
var preorderTraversal = function(tree) {
  let res = [];
  // 遍历函数fun
  function traversal(node) {
      if (node !== null) {
          // 访问根节点的值
          res.push(node.element);
          if (node.left) {
              // 递归遍历左子树
              console.log(node.left.element);
              traversal(node.left);
          };
          if (node.right) {
              // 递归遍历右子树
              console.log(node.right.element);
              traversal(node.right);
          };
      };
  };
  traversal(tree.root);
  return res;
};

let tree = new Tree();
[10, 8, 19, 6, 15, 22, 20].forEach(i=>{
  tree.add(i)
})
let result = preorderTraversal(tree);
console.log(result);